package com.alit.face.koala.service;

import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alit.face.koala.entity.KoalaCemara;
import com.alit.face.koala.repository.KoalaCemaraRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * @author litong
 * @date 2019年4月27日_上午11:41:33
 * @version 1.0
 */
@Service
@Slf4j
public class KoalaCemaraService {
  @Autowired
  private KoalaCemaraRepository koalaCemaraRepository;

  /**
   * 保存screenToken到数据库,如果数据库中存在screenToken不保存,更新时间
   * 
   * @param screen
   * @return
   */
  @SuppressWarnings("serial")
  public boolean saveScreenToken(String screenToken, Long timestramp) {
    Specification<KoalaCemara> specification = new Specification<KoalaCemara>() {

      @Override
      public Predicate toPredicate(Root<KoalaCemara> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        Path<String> path = root.<String> get(KoalaCemara._screen_token); // 获取要操作的字段
        Predicate equal = criteriaBuilder.equal(path, screenToken);
        return equal;
      }
    };
    // 执行查询
    Optional<KoalaCemara> findOne = koalaCemaraRepository.findOne(specification);
    try {
      KoalaCemara koalaCemara = findOne.get();
      koalaCemara.setLastUpdateTime(timestramp);
      koalaCemaraRepository.save(koalaCemara);
      return true;
    } catch (Exception e) {
      // 发送异常,数据中不存在,保存screenToken
      KoalaCemara koalaCemara = new KoalaCemara();
      koalaCemara.setLastUpdateTime(timestramp);
      koalaCemara.setScreen_token(screenToken);
      koalaCemaraRepository.save(koalaCemara);
    }
    return true;
  }

  /**
   * 根据screenToken查询主题
   * 
   * @param screenToken
   * @return
   */
  public KoalaCemara findTopic(String screenToken) {
    // 创建Specification实例
    Specification<KoalaCemara> s = (Root<KoalaCemara> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> {
      Path<String> scp = root.<String> get(KoalaCemara._screen_token); // screen toekn path
      Predicate equal = builder.equal(scp, screenToken);
      return equal;
    };
    Optional<KoalaCemara> findOne = koalaCemaraRepository.findOne(s);
    try {
      return findOne.get();
    } catch (Exception e) {
      log.error("没有配置通道:"+screenToken);
    }
    return null;
  }
}
